﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chat_D_LuX_Client
{
    class BroadcastorCallback : BroadcastorServiceRef.IBroadcastorServiceCallback
    {
        private System.Threading.SynchronizationContext syncContext =
            AsyncOperationManager.SynchronizationContext;
        private EventHandler _broadcastorCallBackHandler;

        /***
         * Used to set the callback handler for the client, use it when you register a client to the service.
         * ***/
        public void SetHandler(EventHandler handler)
        {
            this._broadcastorCallBackHandler = handler;
        }

        /***
         * Allows the service to call the client
         * ***/
        public void BroadcastToClient(BroadcastorServiceRef.EventDataType eventData)
        {
            syncContext.Post(new System.Threading.SendOrPostCallback(OnBroadcast),
                eventData);
        }

        /***
         * This is the connection between the client callback handler (SetHandler method) and the actual service call,
         * which is invoked by the service through BroadcastToClient method.
         * When the service calls BroadcastToClient, the call is delegated to this method and then the same call will
         * be delegated to the client callback handler
         * ***/
        private void OnBroadcast(object eventData)
        {
            this._broadcastorCallBackHandler.Invoke(eventData, null);
        }
    }
}
